<?php

namespace frontend\controllers;

use bc\api\SzApi;
use bc\controller\SampleController;
use bc\model\ItemdataModel;
use bc\model\ItemdetailModel;
use bc\model\ItemModel;
use bc\model\OrderbindMode;
use yii\web\Session;

class ItemdataController extends SampleController
{
    public function  actionSave()
    {   
        
        
        $dataInfo = $_POST;
        //var_dump($_POST);die();     
        $sexD = array(
            30 => 1,
            31 => 0
        );
        $session = new Session ();
        $shop_user = $session->get('shop_user');
        
        $bind_id = $dataInfo['bind_id'];
        $bind_no = $dataInfo['bind_no'];
        unset($dataInfo['bind_id']);
        unset($dataInfo['bind_no']);
        //$transaction = $this->getDb()->beginTransaction();
        //获取用户姓名和生日和性别，样本编号。//检测人性别，0表示男，1表示女
       
        //判断data表中是否已有绑定信息，有则删除后添加，没有则添加
        $datamodel = new ItemdataModel();
        if($itemIds = $datamodel->insertByBindId($bind_id))
        {
            //删除item_data表
            $sql = "delete from bc_item_data where bind_id = $bind_id";
            $datamodel->getDb()->createCommand($sql)->execute();
            //删除item_detail表

            //var_dump($itemIds);die();
            $newIds = '';
            //$sql = "delete from bc_item_detail where id"
            foreach($itemIds as $key=>$value){
                foreach($value as $k=>$v){
                    $newIds = ($newIds == '')? "{$v}": $newIds .",{$v}";
                }
            }
            $newIds = "(".$newIds.")";
            //var_dump($newIds);die();
            $detailmodel = new ItemdetailModel();
            $sql = "delete from bc_item_detail where item_data_id in {$newIds} ";
            $detailmodel->getDb()->createCommand($sql)->execute();
       
        }
        
        
        if($dataInfo['product_id'] == 2){
        $orderbindM = new OrderbindMode();
        $orderbindM->autoId='bind_id';
        $orderbindD=$orderbindM->getRowById($bind_id);
        $params ['sampleNo'] =$orderbindD['bind_no'];
        $params ['name'] = $dataInfo['item1'];
        $params ['sex'] = $sexD[$dataInfo['item2'][0]];
        $params ['birthday'] = $dataInfo['item3'];
        $szApiM = new SzApi();
        $szApiD = json_decode($szApiM->SampleChecker($params),true);
        if($szApiD['retCode'] !== 0)
        {
            $url = '/bind/sample/info?bindno='.$bind_no.'&bindid='.$bind_id;
            echo '<script type="text/javascript">';
            //echo 'alert('. '\''.$szApiD['msg'] .'\'' .'); ';
            echo 'alert('. '\''.'数据提交失败，请联系客服^-^' .'\'' .'); ';
            echo "window.location.href='{$url}'; ";
            echo '</script>';
//            sleep(3);
//            $this->redirect(\Yii::$app->request->getHostInfo().'/bind/sample/info?bindno='.$bind_no.'&bindid='.$bind_id);
        }
         }

       
        if(\Yii::$app->request->post())
        {    //遍历表单获取的所有name 和 value
             
            foreach ($dataInfo as $keys=>$values)
            {
                $itemName = substr($keys,0,4);
                if ($itemName == "item")
                {
                    // item data insert
                    $data['item_product_id'] = substr($keys,4);
                    if(is_array($values)){
                        $newvalues = implode(',', $values);
                        $data['item_value'] = $newvalues;
                    }else{
                        $data['item_value']=  $values;

                    }

                    $data['user_id'] = $shop_user['user_id'];
                    $item_product_id = $data['item_product_id'];
                    //获取item_data_id
                    $sql = 'INSERT INTO ' . ' bc_item_data ' . "(item_product_id, item_value,bind_id, user_id ) VALUES ( {$data['item_product_id']}, '{$data['item_value']}',$bind_id,{$data['user_id'] })";
                    $datamodel->getDb()->createCommand($sql)->execute();
                    $item_data_id=$datamodel->getDb()->getLastInsertID();
//                    $item_data_id = $datamodel -> add($data);

                    //根据item_product_id 查询出item_type
                    $itemmodel = new ItemModel();
                    $item_type = $itemmodel->getItemTypeByProductId($data['item_product_id']);
                    //var_dump($item_type);die();
                    if($item_type == "2" || $item_type == "3")
                    {
                        //insert detail  

                        $detailmodel = new ItemdetailModel();
                        //选其他
                        $subitemKey =  $this-> getSubitemKey( $_POST,'subitem'.$item_product_id );// subitem5_6 6 subitem_id  subitemp6_6 subitemp7_6
                        $subitemValue = $_POST[$subitemKey];

                        if( strpos($subitemKey,'_') )
                        {
                            $data1['item_data_id'] = $item_data_id;

                            $num = strpos($subitemKey,'_');
                            $newsubitemKey = substr($subitemKey , $num+1);
                            $data1['subitem_id'] = $newsubitemKey;
                            $data1['subitem_value'] = !empty($subitemValue)?$subitemValue:'其他';
                            $detailmodel->add($data1);

                        }

                        //单选、多选
                        if(is_array($values)){

                            $detailmodel ->tractionInsert($item_data_id,$values,$newsubitemKey);

                        }else{
                            if( $values  !=  $newsubitemKey){
                                $data2['item_data_id'] = $item_data_id;
                                $data2['subitem_id'] = $values;
                                $data2['subitem_value'] = '1';
                                $detailmodel->add($data2);
                            }


                        }

                    }
                }
            }
        }
        $view["product_id"]=$dataInfo['product_id'];
        $this->getHtmlFromPid($dataInfo['product_id']);
        $view ['product_html']=$this->html;
        return $this->render ( '/bind/sample/success',$view);
        //$transaction->commit();
    }

    public function  getSubitemKey($data,$name)
    {
        foreach ($data as $k=>$v)
        {
            $num1 = strpos($k,'_');
            if (substr($k, 0, $num1 ) == $name )
            {
                return $k;
            }
        }
    }


}

